home *** CD-ROM | disk | FTP | other *** search
/ PC World 2008 February (DVD) / PCWorld_2008-02_DVD.iso / v cisle / PHP / PHP.exe / xampp-win32-1.6.5-installer.exe / mysql / scripts / mysqlhotcopy < prev   
Encoding:
Text File  |  2007-12-20  |  32.1 KB  |  1,141 lines

  1. #!@PERL@ -w
  2.  
  3. use strict;
  4. use Getopt::Long;
  5. use Data::Dumper;
  6. use File::Basename;
  7. use File::Path;
  8. use DBI;
  9. use Sys::Hostname;
  10. use File::Copy;
  11. use File::Temp qw(tempfile);
  12.  
  13. =head1 NAME
  14.  
  15. mysqlhotcopy - fast on-line hot-backup utility for local MySQL databases and tables
  16.  
  17. =head1 SYNOPSIS
  18.  
  19.   mysqlhotcopy db_name
  20.  
  21.   mysqlhotcopy --suffix=_copy db_name_1 ... db_name_n
  22.  
  23.   mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory
  24.  
  25.   mysqlhotcopy db_name./regex/
  26.  
  27.   mysqlhotcopy db_name./^\(foo\|bar\)/
  28.  
  29.   mysqlhotcopy db_name./~regex/
  30.  
  31.   mysqlhotcopy db_name_1./regex_1/ db_name_1./regex_2/ ... db_name_n./regex_n/ /path/to/new_directory
  32.  
  33.   mysqlhotcopy --method='scp -Bq -i /usr/home/foo/.ssh/identity' --user=root --password=secretpassword \
  34.          db_1./^nice_table/ user@some.system.dom:~/path/to/new_directory
  35.  
  36. WARNING: THIS PROGRAM IS STILL IN BETA. Comments/patches welcome.
  37.  
  38. =cut
  39.  
  40. # Documentation continued at end of file
  41.  
  42. my $VERSION = "1.22";
  43.  
  44. my $opt_tmpdir = $ENV{TMPDIR} || "/tmp";
  45.  
  46. my $OPTIONS = <<"_OPTIONS";
  47.  
  48. $0 Ver $VERSION
  49.  
  50. Usage: $0 db_name[./table_regex/] [new_db_name | directory]
  51.  
  52.   -?, --help           display this helpscreen and exit
  53.   -u, --user=#         user for database login if not current user
  54.   -p, --password=#     password to use when connecting to server (if not set
  55.                        in my.cnf, which is recommended)
  56.   -h, --host=#         Hostname for local server when connecting over TCP/IP
  57.   -P, --port=#         port to use when connecting to local server with TCP/IP
  58.   -S, --socket=#       socket to use when connecting to local server
  59.  
  60.   --allowold           don\'t abort if target dir already exists (rename it _old)
  61.   --addtodest          don\'t rename target dir if it exists, just add files to it
  62.   --keepold            don\'t delete previous (now renamed) target when done
  63.   --noindices          don\'t include full index files in copy
  64.   --method=#           method for copy (only "cp" currently supported)
  65.  
  66.   -q, --quiet          be silent except for errors
  67.   --debug              enable debug
  68.   -n, --dryrun         report actions without doing them
  69.  
  70.   --regexp=#           copy all databases with names matching regexp
  71.   --suffix=#           suffix for names of copied databases
  72.   --checkpoint=#       insert checkpoint entry into specified db.table
  73.   --flushlog           flush logs once all tables are locked 
  74.   --resetmaster        reset the binlog once all tables are locked
  75.   --resetslave         reset the master.info once all tables are locked
  76.   --tmpdir=#           temporary directory (instead of $opt_tmpdir)
  77.   --record_log_pos=#   record slave and master status in specified db.table
  78.   --chroot=#           base directory of chroot jail in which mysqld operates
  79.  
  80.   Try \'perldoc $0\' for more complete documentation
  81. _OPTIONS
  82.  
  83. sub usage {
  84.     die @_, $OPTIONS;
  85. }
  86.  
  87. # Do not initialize user or password options; that way, any user/password
  88. # options specified in option files will be used.  If no values are specified
  89. # all, the defaults will be used (login name, no password).
  90.  
  91. my %opt = (
  92.     noindices    => 0,
  93.     allowold    => 0,    # for safety
  94.     keepold    => 0,
  95.     method    => "cp",
  96.     flushlog    => 0,
  97. );
  98. Getopt::Long::Configure(qw(no_ignore_case)); # disambuguate -p and -P
  99. GetOptions( \%opt,
  100.     "help",
  101.     "host|h=s",
  102.     "user|u=s",
  103.     "password|p=s",
  104.     "port|P=s",
  105.     "socket|S=s",
  106.     "allowold!",
  107.     "keepold!",
  108.     "addtodest!",
  109.     "noindices!",
  110.     "method=s",
  111.     "debug",
  112.     "quiet|q",
  113.     "mv!",
  114.     "regexp=s",
  115.     "suffix=s",
  116.     "checkpoint=s",
  117.     "record_log_pos=s",
  118.     "flushlog",
  119.     "resetmaster",
  120.     "resetslave",
  121.     "tmpdir|t=s",
  122.     "dryrun|n",
  123.     "chroot=s",
  124. ) or usage("Invalid option");
  125.  
  126. # @db_desc
  127. # ==========
  128. # a list of hash-refs containing:
  129. #
  130. #   'src'     - name of the db to copy
  131. #   't_regex' - regex describing tables in src
  132. #   'target'  - destination directory of the copy
  133. #   'tables'  - array-ref to list of tables in the db
  134. #   'files'   - array-ref to list of files to be copied
  135. #               (RAID files look like 'nn/name.MYD')
  136. #   'index'   - array-ref to list of indexes to be copied
  137. #
  138.  
  139. my @db_desc = ();
  140. my $tgt_name = undef;
  141.  
  142. usage("") if ($opt{help});
  143.  
  144. if ( $opt{regexp} || $opt{suffix} || @ARGV > 2 ) {
  145.     $tgt_name   = pop @ARGV unless ( exists $opt{suffix} );
  146.     @db_desc = map { s{^([^\.]+)\./(.+)/$}{$1}; { 'src' => $_, 't_regex' => ( $2 ? $2 : '.*' ) } } @ARGV;
  147. }
  148. else {
  149.     usage("Database name to hotcopy not specified") unless ( @ARGV );
  150.  
  151.     $ARGV[0] =~ s{^([^\.]+)\./(.+)/$}{$1};
  152.     @db_desc = ( { 'src' => $ARGV[0], 't_regex' => ( $2 ? $2 : '.*' ) } );
  153.  
  154.     if ( @ARGV == 2 ) {
  155.     $tgt_name   = $ARGV[1];
  156.     }
  157.     else {
  158.     $opt{suffix} = "_copy";
  159.     }
  160. }
  161.  
  162. my %mysqld_vars;
  163. my $start_time = time;
  164. $opt_tmpdir= $opt{tmpdir} if $opt{tmpdir};
  165. $0 = $1 if $0 =~ m:/([^/]+)$:;
  166. $opt{quiet} = 0 if $opt{debug};
  167. $opt{allowold} = 1 if $opt{keepold};
  168.  
  169. # --- connect to the database ---
  170. my $dsn;
  171. $dsn  = ";host=" . (defined($opt{host}) ? $opt{host} : "localhost");
  172. $dsn .= ";port=$opt{port}" if $opt{port};
  173. $dsn .= ";mysql_socket=$opt{socket}" if $opt{socket};
  174.  
  175. # use mysql_read_default_group=mysqlhotcopy so that [client] and
  176. # [mysqlhotcopy] groups will be read from standard options files.
  177.  
  178. my $dbh = DBI->connect("dbi:mysql:$dsn;mysql_read_default_group=mysqlhotcopy",
  179.                         $opt{user}, $opt{password},
  180. {
  181.     RaiseError => 1,
  182.     PrintError => 0,
  183.     AutoCommit => 1,
  184. });
  185.  
  186. # --- check that checkpoint table exists if specified ---
  187. if ( $opt{checkpoint} ) {
  188.     $opt{checkpoint} = quote_names( $opt{checkpoint} );
  189.     eval { $dbh->do( qq{ select time_stamp, src, dest, msg 
  190.              from $opt{checkpoint} where 1 != 1} );
  191.        };
  192.  
  193.     die "Error accessing Checkpoint table ($opt{checkpoint}): $@"
  194.       if ( $@ );
  195. }
  196.  
  197. # --- check that log_pos table exists if specified ---
  198. if ( $opt{record_log_pos} ) {
  199.     $opt{record_log_pos} = quote_names( $opt{record_log_pos} );
  200.  
  201.     eval { $dbh->do( qq{ select host, time_stamp, log_file, log_pos, master_host, master_log_file, master_log_pos
  202.              from $opt{record_log_pos} where 1 != 1} );
  203.        };
  204.  
  205.     die "Error accessing log_pos table ($opt{record_log_pos}): $@"
  206.       if ( $@ );
  207. }
  208.  
  209. # --- get variables from database ---
  210. my $sth_vars = $dbh->prepare("show variables like 'datadir'");
  211. $sth_vars->execute;
  212. while ( my ($var,$value) = $sth_vars->fetchrow_array ) {
  213.     $mysqld_vars{ $var } = $value;
  214. }
  215. my $datadir = $mysqld_vars{'datadir'}
  216.     || die "datadir not in mysqld variables";
  217.     $datadir= $opt{chroot}.$datadir if ($opt{chroot});
  218. $datadir =~ s:/$::;
  219.  
  220.  
  221. # --- get target path ---
  222. my ($tgt_dirname, $to_other_database);
  223. $to_other_database=0;
  224. if (defined($tgt_name) && $tgt_name =~ m:^\w+$: && @db_desc <= 1)
  225. {
  226.     $tgt_dirname = "$datadir/$tgt_name";
  227.     $to_other_database=1;
  228. }
  229. elsif (defined($tgt_name) && ($tgt_name =~ m:/: || $tgt_name eq '.')) {
  230.     $tgt_dirname = $tgt_name;
  231. }
  232. elsif ( $opt{suffix} ) {
  233.     print "Using copy suffix '$opt{suffix}'\n" unless $opt{quiet};
  234. }
  235. elsif ( ($^O =~ m/^(NetWare)$/) && defined($tgt_name) && ($tgt_name =~ m:\\: || $tgt_name eq '.'))  
  236. {
  237.     $tgt_dirname = $tgt_name;
  238. }
  239. else
  240. {
  241.   $tgt_name="" if (!defined($tgt_name));
  242.   die "Target '$tgt_name' doesn't look like a database name or directory path.\n";
  243. }
  244.  
  245. # --- resolve database names from regexp ---
  246. if ( defined $opt{regexp} ) {
  247.     my $t_regex = '.*';
  248.     if ( $opt{regexp} =~ s{^/(.+)/\./(.+)/$}{$1} ) {
  249.         $t_regex = $2;
  250.     }
  251.  
  252.     my $sth_dbs = $dbh->prepare("show databases");
  253.     $sth_dbs->execute;
  254.     while ( my ($db_name) = $sth_dbs->fetchrow_array ) {
  255.     next if $db_name =~ m/^information_schema$/i;
  256.     push @db_desc, { 'src' => $db_name, 't_regex' => $t_regex } if ( $db_name =~ m/$opt{regexp}/o );
  257.     }
  258. }
  259.  
  260. # --- get list of tables to hotcopy ---
  261.  
  262. my $hc_locks = "";
  263. my $hc_tables = "";
  264. my $num_tables = 0;
  265. my $num_files = 0;
  266. my $raid_dir_regex = '[A-Za-z0-9]{2}';
  267.  
  268. foreach my $rdb ( @db_desc ) {
  269.     my $db = $rdb->{src};
  270.     my @dbh_tables = get_list_of_tables( $db );
  271.  
  272.     ## generate regex for tables/files
  273.     my $t_regex;
  274.     my $negated;
  275.     if ($rdb->{t_regex}) {
  276.         $t_regex = $rdb->{t_regex};        ## assign temporary regex
  277.         $negated = $t_regex =~ s/^~//;     ## note and remove negation operator
  278.  
  279.         $t_regex = qr/$t_regex/;           ## make regex string from
  280.                                            ## user regex
  281.  
  282.         ## filter (out) tables specified in t_regex
  283.         print "Filtering tables with '$t_regex'\n" if $opt{debug};
  284.         @dbh_tables = ( $negated 
  285.                         ? grep { $_ !~ $t_regex } @dbh_tables
  286.                         : grep { $_ =~ $t_regex } @dbh_tables );
  287.     }
  288.  
  289.     ## get list of files to copy
  290.     my $db_dir = "$datadir/$db";
  291.     opendir(DBDIR, $db_dir ) 
  292.       or die "Cannot open dir '$db_dir': $!";
  293.  
  294.     my %db_files;
  295.     my @raid_dir = ();
  296.  
  297.     while ( defined( my $name = readdir DBDIR ) ) {
  298.     if ( $name =~ /^$raid_dir_regex$/ && -d "$db_dir/$name" ) {
  299.         push @raid_dir, $name;
  300.     }
  301.     else {
  302.         $db_files{$name} = $1 if ( $name =~ /(.+)\.\w+$/ );
  303.         }
  304.     }
  305.     closedir( DBDIR );
  306.  
  307.     scan_raid_dir( \%db_files, $db_dir, @raid_dir );
  308.  
  309.     unless( keys %db_files ) {
  310.     warn "'$db' is an empty database\n";
  311.     }
  312.  
  313.     ## filter (out) files specified in t_regex
  314.     my @db_files;
  315.     if ($rdb->{t_regex}) {
  316.         @db_files = ($negated
  317.                      ? grep { $db_files{$_} !~ $t_regex } keys %db_files
  318.                      : grep { $db_files{$_} =~ $t_regex } keys %db_files );
  319.     }
  320.     else {
  321.         @db_files = keys %db_files;
  322.     }
  323.  
  324.     @db_files = sort @db_files;
  325.  
  326.     my @index_files=();
  327.  
  328.     ## remove indices unless we're told to keep them
  329.     if ($opt{noindices}) {
  330.         @index_files= grep { /\.(ISM|MYI)$/ } @db_files;
  331.     @db_files = grep { not /\.(ISM|MYI)$/ } @db_files;
  332.     }
  333.  
  334.     $rdb->{files}  = [ @db_files ];
  335.     $rdb->{index}  = [ @index_files ];
  336.     my @hc_tables = map { quote_names("$db.$_") } @dbh_tables;
  337.     $rdb->{tables} = [ @hc_tables ];
  338.  
  339.     $rdb->{raid_dirs} = [ get_raid_dirs( $rdb->{files} ) ];
  340.  
  341.     $hc_locks .= ", "  if ( length $hc_locks && @hc_tables );
  342.     $hc_locks .= join ", ", map { "$_ READ" } @hc_tables;
  343.     $hc_tables .= ", "  if ( length $hc_tables && @hc_tables );
  344.     $hc_tables .= join ", ", @hc_tables;
  345.  
  346.     $num_tables += scalar @hc_tables;
  347.     $num_files  += scalar @{$rdb->{files}};
  348. }
  349.  
  350. # --- resolve targets for copies ---
  351.  
  352. if (defined($tgt_name) && length $tgt_name ) {
  353.     # explicit destination directory specified
  354.  
  355.     # GNU `cp -r` error message
  356.     die "copying multiple databases, but last argument ($tgt_dirname) is not a directory\n"
  357.       if ( @db_desc > 1 && !(-e $tgt_dirname && -d $tgt_dirname ) );
  358.  
  359.     if ($to_other_database)
  360.     {
  361.       foreach my $rdb ( @db_desc ) {
  362.     $rdb->{target} = "$tgt_dirname";
  363.       }
  364.     }
  365.     elsif ($opt{method} =~ /^scp\b/) 
  366.     {   # we have to trust scp to hit the target
  367.     foreach my $rdb ( @db_desc ) {
  368.         $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  369.     }
  370.     }
  371.     else
  372.     {
  373.       die "Last argument ($tgt_dirname) is not a directory\n"
  374.     if (!(-e $tgt_dirname && -d $tgt_dirname ) );
  375.       foreach my $rdb ( @db_desc ) {
  376.     $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  377.       }
  378.     }
  379.   }
  380. else {
  381.   die "Error: expected \$opt{suffix} to exist" unless ( exists $opt{suffix} );
  382.  
  383.   foreach my $rdb ( @db_desc ) {
  384.     $rdb->{target} = "$datadir/$rdb->{src}$opt{suffix}";
  385.   }
  386. }
  387.  
  388. print Dumper( \@db_desc ) if ( $opt{debug} );
  389.  
  390. # --- bail out if all specified databases are empty ---
  391.  
  392. die "No tables to hot-copy" unless ( length $hc_locks );
  393.  
  394. # --- create target directories if we are using 'cp' ---
  395.  
  396. my @existing = ();
  397.  
  398. if ($opt{method} =~ /^cp\b/)
  399. {
  400.   foreach my $rdb ( @db_desc ) {
  401.     push @existing, $rdb->{target} if ( -d  $rdb->{target} );
  402.   }
  403.  
  404.   if ( @existing && !($opt{allowold} || $opt{addtodest}) )
  405.   {
  406.     $dbh->disconnect();
  407.     die "Can't hotcopy to '", join( "','", @existing ), "' because directory\nalready exist and the --allowold or --addtodest options were not given.\n"
  408.   }
  409. }
  410.  
  411. retire_directory( @existing ) if @existing && !$opt{addtodest};
  412.  
  413. foreach my $rdb ( @db_desc ) {
  414.     foreach my $td ( '', @{$rdb->{raid_dirs}} ) {
  415.  
  416.     my $tgt_dirpath = "$rdb->{target}/$td";
  417.     # Remove trailing slashes (needed for Mac OS X)
  418.         substr($tgt_dirpath, 1) =~ s|/+$||;
  419.     if ( $opt{dryrun} ) {
  420.         print "mkdir $tgt_dirpath, 0750\n";
  421.     }
  422.     elsif ($opt{method} =~ /^scp\b/) {
  423.         ## assume it's there?
  424.         ## ...
  425.     }
  426.     else {
  427.         mkdir($tgt_dirpath, 0750) or die "Can't create '$tgt_dirpath': $!\n"
  428.         unless -d $tgt_dirpath;
  429.          if ($^O !~ m/^(NetWare)$/)  
  430.             {
  431.         my @f_info= stat "$datadir/$rdb->{src}";
  432.         chown $f_info[4], $f_info[5], $tgt_dirpath;
  433.             }
  434.     }
  435.     }
  436. }
  437.  
  438. ##############################
  439. # --- PERFORM THE HOT-COPY ---
  440. #
  441. # Note that we try to keep the time between the LOCK and the UNLOCK
  442. # as short as possible, and only start when we know that we should
  443. # be able to complete without error.
  444.  
  445. # read lock all the tables we'll be copying
  446. # in order to get a consistent snapshot of the database
  447.  
  448. if ( $opt{checkpoint} || $opt{record_log_pos} ) {
  449.   # convert existing READ lock on checkpoint and/or log_pos table into WRITE lock
  450.   foreach my $table ( grep { defined } ( $opt{checkpoint}, $opt{record_log_pos} ) ) {
  451.     $hc_locks .= ", $table WRITE" 
  452.     unless ( $hc_locks =~ s/$table\s+READ/$table WRITE/ );
  453.   }
  454. }
  455.  
  456. my $hc_started = time;    # count from time lock is granted
  457.  
  458. if ( $opt{dryrun} ) {
  459.     print "LOCK TABLES $hc_locks\n";
  460.     print "FLUSH TABLES /*!32323 $hc_tables */\n";
  461.     print "FLUSH LOGS\n" if ( $opt{flushlog} );
  462.     print "RESET MASTER\n" if ( $opt{resetmaster} );
  463.     print "RESET SLAVE\n" if ( $opt{resetslave} );
  464. }
  465. else {
  466.     my $start = time;
  467.     $dbh->do("LOCK TABLES $hc_locks");
  468.     printf "Locked $num_tables tables in %d seconds.\n", time-$start unless $opt{quiet};
  469.     $hc_started = time;    # count from time lock is granted
  470.  
  471.     # flush tables to make on-disk copy uptodate
  472.     $start = time;
  473.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  474.     printf "Flushed tables ($hc_tables) in %d seconds.\n", time-$start unless $opt{quiet};
  475.     $dbh->do( "FLUSH LOGS" ) if ( $opt{flushlog} );
  476.     $dbh->do( "RESET MASTER" ) if ( $opt{resetmaster} );
  477.     $dbh->do( "RESET SLAVE" ) if ( $opt{resetslave} );
  478.  
  479.     if ( $opt{record_log_pos} ) {
  480.     record_log_pos( $dbh, $opt{record_log_pos} );
  481.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  482.     }
  483. }
  484.  
  485. my @failed = ();
  486.  
  487. foreach my $rdb ( @db_desc )
  488. {
  489.   my @files = map { "$datadir/$rdb->{src}/$_" } @{$rdb->{files}};
  490.   next unless @files;
  491.   
  492.   eval { copy_files($opt{method}, \@files, $rdb->{target}, $rdb->{raid_dirs} ); };
  493.   push @failed, "$rdb->{src} -> $rdb->{target} failed: $@"
  494.     if ( $@ );
  495.   
  496.   @files = @{$rdb->{index}};
  497.   if ($rdb->{index})
  498.   {
  499.     copy_index($opt{method}, \@files,
  500.            "$datadir/$rdb->{src}", $rdb->{target} );
  501.   }
  502.   
  503.   if ( $opt{checkpoint} ) {
  504.     my $msg = ( $@ ) ? "Failed: $@" : "Succeeded";
  505.     
  506.     eval {
  507.       $dbh->do( qq{ insert into $opt{checkpoint} (src, dest, msg) 
  508.               VALUES ( '$rdb->{src}', '$rdb->{target}', '$msg' )
  509.             } ); 
  510.     };
  511.     
  512.     if ( $@ ) {
  513.       warn "Failed to update checkpoint table: $@\n";
  514.     }
  515.   }
  516. }
  517.  
  518. if ( $opt{dryrun} ) {
  519.     print "UNLOCK TABLES\n";
  520.     if ( @existing && !$opt{keepold} ) {
  521.     my @oldies = map { $_ . '_old' } @existing;
  522.     print "rm -rf @oldies\n" 
  523.     }
  524.     $dbh->disconnect();
  525.     exit(0);
  526. }
  527. else {
  528.     $dbh->do("UNLOCK TABLES");
  529. }
  530.  
  531. my $hc_dur = time - $hc_started;
  532. printf "Unlocked tables.\n" unless $opt{quiet};
  533.  
  534. #
  535. # --- HOT-COPY COMPLETE ---
  536. ###########################
  537.  
  538. $dbh->disconnect;
  539.  
  540. if ( @failed ) {
  541.     # hotcopy failed - cleanup
  542.     # delete any @targets 
  543.     # rename _old copy back to original
  544.  
  545.     my @targets = ();
  546.     foreach my $rdb ( @db_desc ) {
  547.         push @targets, $rdb->{target} if ( -d  $rdb->{target} );
  548.     }
  549.     print "Deleting @targets \n" if $opt{debug};
  550.  
  551.     print "Deleting @targets \n" if $opt{debug};
  552.     rmtree([@targets]);
  553.     if (@existing) {
  554.     print "Restoring @existing from back-up\n" if $opt{debug};
  555.         foreach my $dir ( @existing ) {
  556.         rename("${dir}_old", $dir )
  557.           or warn "Can't rename ${dir}_old to $dir: $!\n";
  558.     }
  559.     }
  560.  
  561.     die join( "\n", @failed );
  562. }
  563. else {
  564.     # hotcopy worked
  565.     # delete _old unless $opt{keepold}
  566.  
  567.     if ( @existing && !$opt{keepold} ) {
  568.     my @oldies = map { $_ . '_old' } @existing;
  569.     print "Deleting previous copy in @oldies\n" if $opt{debug};
  570.     rmtree([@oldies]);
  571.     }
  572.  
  573.     printf "$0 copied %d tables (%d files) in %d second%s (%d seconds overall).\n",
  574.         $num_tables, $num_files,
  575.         $hc_dur, ($hc_dur==1)?"":"s", time - $start_time
  576.     unless $opt{quiet};
  577. }
  578.  
  579. exit 0;
  580.  
  581.  
  582. # ---
  583.  
  584. sub copy_files {
  585.     my ($method, $files, $target, $raid_dirs) = @_;
  586.     my @cmd;
  587.     print "Copying ".@$files." files...\n" unless $opt{quiet};
  588.  
  589.     if ($^O =~ m/^(NetWare)$/)  # on NetWare call PERL copy (slower)
  590.     {
  591.       foreach my $file ( @$files )
  592.       {
  593.         copy($file, $target."/".basename($file));
  594.       }
  595.     }
  596.     elsif ($method =~ /^s?cp\b/)  # cp or scp with optional flags
  597.     {
  598.     my $cp = $method;
  599.     # add option to preserve mod time etc of copied files
  600.     # not critical, but nice to have
  601.     $cp.= " -p" if $^O =~ m/^(solaris|linux|freebsd|darwin)$/;
  602.  
  603.     # add recursive option for scp
  604.     $cp.= " -r" if $^O =~ /m^(solaris|linux|freebsd|darwin)$/ && $method =~ /^scp\b/;
  605.  
  606.     my @non_raid = map { "'$_'" } grep { ! m:/$raid_dir_regex/[^/]+$: } @$files;
  607.  
  608.     # add files to copy and the destination directory
  609.     safe_system( $cp, @non_raid, "'$target'" ) if (@non_raid);
  610.     
  611.     foreach my $rd ( @$raid_dirs ) {
  612.         my @raid = map { "'$_'" } grep { m:$rd/: } @$files;
  613.         safe_system( $cp, @raid, "'$target'/$rd" ) if ( @raid );
  614.     }
  615.     }
  616.     else
  617.     {
  618.     die "Can't use unsupported method '$method'\n";
  619.     }
  620. }
  621.  
  622. #
  623. # Copy only the header of the index file
  624. #
  625.  
  626. sub copy_index
  627. {
  628.   my ($method, $files, $source, $target) = @_;
  629.   
  630.   print "Copying indices for ".@$files." files...\n" unless $opt{quiet};  
  631.   foreach my $file (@$files)
  632.   {
  633.     my $from="$source/$file";
  634.     my $to="$target/$file";
  635.     my $buff;
  636.     open(INPUT, "<$from") || die "Can't open file $from: $!\n";
  637.     binmode(INPUT, ":raw");
  638.     my $length=read INPUT, $buff, 2048;
  639.     die "Can't read index header from $from\n" if ($length < 1024);
  640.     close INPUT;
  641.     
  642.     if ( $opt{dryrun} )
  643.     {
  644.       print "$opt{method}-header $from $to\n";
  645.     }
  646.     elsif ($opt{method} eq 'cp')
  647.     {
  648.       open(OUTPUT,">$to")   || die "Can\'t create file $to: $!\n";
  649.       if (syswrite(OUTPUT,$buff) != length($buff))
  650.       {
  651.     die "Error when writing data to $to: $!\n";
  652.       }
  653.       close OUTPUT       || die "Error on close of $to: $!\n";
  654.     }
  655.     elsif ($opt{method} =~ /^scp\b/)
  656.     {
  657.       my ($fh, $tmp)= tempfile('mysqlhotcopy-XXXXXX', DIR => $opt_tmpdir) or
  658.     die "Can\'t create/open file in $opt_tmpdir\n";
  659.       if (syswrite($fh,$buff) != length($buff))
  660.       {
  661.     die "Error when writing data to $tmp: $!\n";
  662.       }
  663.       close $fh || die "Error on close of $tmp: $!\n";
  664.       safe_system("$opt{method} $tmp $to");
  665.       unlink $tmp;
  666.     }
  667.     else
  668.     {
  669.       die "Can't use unsupported method '$opt{method}'\n";
  670.     }
  671.   }
  672. }
  673.  
  674.  
  675. sub safe_system {
  676.   my @sources= @_;
  677.   my $method= shift @sources;
  678.   my $target= pop @sources;
  679.   ## @sources = list of source file names
  680.  
  681.   ## We have to deal with very long command lines, otherwise they may generate 
  682.   ## "Argument list too long".
  683.   ## With 10000 tables the command line can be around 1MB, much more than 128kB
  684.   ## which is the common limit on Linux (can be read from
  685.   ## /usr/src/linux/include/linux/binfmts.h
  686.   ## see http://www.linuxjournal.com/article.php?sid=6060).
  687.  
  688.   my $chunk_limit= 100 * 1024; # 100 kB
  689.   my @chunk= (); 
  690.   my $chunk_length= 0;
  691.   foreach (@sources) {
  692.       push @chunk, $_;
  693.       $chunk_length+= length($_);
  694.       if ($chunk_length > $chunk_limit) {
  695.           safe_simple_system($method, @chunk, $target);
  696.           @chunk=();
  697.           $chunk_length= 0;
  698.       }
  699.   }
  700.   if ($chunk_length > 0) { # do not forget last small chunk
  701.       safe_simple_system($method, @chunk, $target); 
  702.   }
  703. }
  704.  
  705. sub safe_simple_system {
  706.     my @cmd= @_;
  707.  
  708.     if ( $opt{dryrun} ) {
  709.         print "@cmd\n";
  710.     }
  711.     else {
  712.         ## for some reason system fails but backticks works ok for scp...
  713.         print "Executing '@cmd'\n" if $opt{debug};
  714.         my $cp_status = system "@cmd > /dev/null";
  715.         if ($cp_status != 0) {
  716.             warn "Executing command failed ($cp_status). Trying backtick execution...\n";
  717.             ## try something else
  718.             `@cmd` || die "Error: @cmd failed ($?) while copying files.\n";
  719.         }
  720.     }
  721. }
  722.  
  723. sub retire_directory {
  724.     my ( @dir ) = @_;
  725.  
  726.     foreach my $dir ( @dir ) {
  727.     my $tgt_oldpath = $dir . '_old';
  728.     if ( $opt{dryrun} ) {
  729.         print "rmtree $tgt_oldpath\n" if ( -d $tgt_oldpath );
  730.         print "rename $dir, $tgt_oldpath\n";
  731.         next;
  732.     }
  733.  
  734.     if ( -d $tgt_oldpath ) {
  735.         print "Deleting previous 'old' hotcopy directory ('$tgt_oldpath')\n" unless $opt{quiet};
  736.         rmtree([$tgt_oldpath],0,1);
  737.     }
  738.     rename($dir, $tgt_oldpath)
  739.       or die "Can't rename $dir=>$tgt_oldpath: $!\n";
  740.     print "Existing hotcopy directory renamed to '$tgt_oldpath'\n" unless $opt{quiet};
  741.     }
  742. }
  743.  
  744. sub record_log_pos {
  745.     my ( $dbh, $table_name ) = @_;
  746.  
  747.     eval {
  748.     my ($file,$position) = get_row( $dbh, "show master status" );
  749.     die "master status is undefined" if !defined $file || !defined $position;
  750.     
  751.     my $row_hash = get_row_hash( $dbh, "show slave status" );
  752.     my ($master_host, $log_file, $log_pos ); 
  753.     if ( $dbh->{mysql_serverinfo} =~ /^3\.23/ ) {
  754.         ($master_host, $log_file, $log_pos ) 
  755.           = @{$row_hash}{ qw / Master_Host Log_File Pos / };
  756.     } else {
  757.         ($master_host, $log_file, $log_pos ) 
  758.           = @{$row_hash}{ qw / Master_Host Master_Log_File Read_Master_Log_Pos / };
  759.     }
  760.     my $hostname = hostname();
  761.     
  762.     $dbh->do( qq{ replace into $table_name 
  763.               set host=?, log_file=?, log_pos=?, 
  764.                           master_host=?, master_log_file=?, master_log_pos=? }, 
  765.           undef, 
  766.           $hostname, $file, $position, 
  767.           $master_host, $log_file, $log_pos  );
  768.     
  769.     };
  770.     
  771.     if ( $@ ) {
  772.     warn "Failed to store master position: $@\n";
  773.     }
  774. }
  775.  
  776. sub get_row {
  777.   my ( $dbh, $sql ) = @_;
  778.  
  779.   my $sth = $dbh->prepare($sql);
  780.   $sth->execute;
  781.   return $sth->fetchrow_array();
  782. }
  783.  
  784. sub get_row_hash {
  785.   my ( $dbh, $sql ) = @_;
  786.  
  787.   my $sth = $dbh->prepare($sql);
  788.   $sth->execute;
  789.   return $sth->fetchrow_hashref();
  790. }
  791.  
  792. sub scan_raid_dir {
  793.     my ( $r_db_files, $data_dir, @raid_dir ) = @_;
  794.  
  795.     local(*RAID_DIR);
  796.     
  797.     foreach my $rd ( @raid_dir ) {
  798.  
  799.     opendir(RAID_DIR, "$data_dir/$rd" ) 
  800.         or die "Cannot open dir '$data_dir/$rd': $!";
  801.  
  802.     while ( defined( my $name = readdir RAID_DIR ) ) {
  803.         $r_db_files->{"$rd/$name"} = $1 if ( $name =~ /(.+)\.\w+$/ );
  804.     }
  805.     closedir( RAID_DIR );
  806.     }
  807. }
  808.  
  809. sub get_raid_dirs {
  810.     my ( $r_files ) = @_;
  811.  
  812.     my %dirs = ();
  813.     foreach my $f ( @$r_files ) {
  814.     if ( $f =~ m:^($raid_dir_regex)/: ) {
  815.         $dirs{$1} = 1;
  816.     }
  817.     }
  818.     return sort keys %dirs;
  819. }
  820.  
  821. sub get_list_of_tables {
  822.     my ( $db ) = @_;
  823.  
  824.     # "use database" cannot cope with database names containing spaces
  825.     # so create a new connection 
  826.  
  827.     my $dbh = DBI->connect("dbi:mysql:${db}${dsn};mysql_read_default_group=mysqlhotcopy",
  828.                 $opt{user}, $opt{password},
  829.     {
  830.     RaiseError => 1,
  831.     PrintError => 0,
  832.     AutoCommit => 1,
  833.     });
  834.  
  835.     my @dbh_tables = eval { $dbh->tables() };
  836.  
  837.     ## Remove quotes around table names
  838.     my $quote = $dbh->get_info(29); # SQL_IDENTIFIER_QUOTE_CHAR
  839.     if ($quote) {
  840.       foreach (@dbh_tables) {
  841.         s/^$quote(.*)$quote$/$1/;
  842.         s/$quote$quote/$quote/g;
  843.       }
  844.     }
  845.  
  846.     $dbh->disconnect();
  847.     return @dbh_tables;
  848. }
  849.  
  850. sub quote_names {
  851.   my ( $name ) = @_;
  852.   # given a db.table name, add quotes
  853.  
  854.   my ($db, $table, @cruft) = split( /\./, $name );
  855.   die "Invalid db.table name '$name'" if (@cruft || !defined $db || !defined $table );
  856.  
  857.   # Earlier versions of DBD return table name non-quoted,
  858.   # such as DBD-2.1012 and the newer ones, such as DBD-2.9002
  859.   # returns it quoted. Let's have a support for both.
  860.   $table=~ s/\`//g;
  861.   return "`$db`.`$table`";
  862. }
  863.  
  864. __END__
  865.  
  866. =head1 DESCRIPTION
  867.  
  868. mysqlhotcopy is designed to make stable copies of live MySQL databases.
  869.  
  870. Here "live" means that the database server is running and the database
  871. may be in active use. And "stable" means that the copy will not have
  872. any corruptions that could occur if the table files were simply copied
  873. without first being locked and flushed from within the server.
  874.  
  875. =head1 OPTIONS
  876.  
  877. =over 4
  878.  
  879. =item --checkpoint checkpoint-table
  880.  
  881. As each database is copied, an entry is written to the specified
  882. checkpoint-table.  This has the happy side-effect of updating the
  883. MySQL update-log (if it is switched on) giving a good indication of
  884. where roll-forward should begin for backup+rollforward schemes.
  885.  
  886. The name of the checkpoint table should be supplied in database.table format.
  887. The checkpoint-table must contain at least the following fields:
  888.  
  889. =over 4
  890.  
  891.   time_stamp timestamp not null
  892.   src varchar(32)
  893.   dest varchar(60)
  894.   msg varchar(255)
  895.  
  896. =back
  897.  
  898. =item --record_log_pos log-pos-table
  899.  
  900. Just before the database files are copied, update the record in the
  901. log-pos-table from the values returned from "show master status" and
  902. "show slave status". The master status values are stored in the
  903. log_file and log_pos columns, and establish the position in the binary
  904. logs that any slaves of this host should adopt if initialised from
  905. this dump.  The slave status values are stored in master_host,
  906. master_log_file, and master_log_pos, and these are useful if the host
  907. performing the dump is a slave and other sibling slaves are to be
  908. initialised from this dump.
  909.  
  910. The name of the log-pos table should be supplied in database.table format.
  911. A sample log-pos table definition:
  912.  
  913. =over 4
  914.  
  915. CREATE TABLE log_pos (
  916.   host            varchar(60) NOT null,
  917.   time_stamp      timestamp(14) NOT NULL,
  918.   log_file        varchar(32) default NULL,
  919.   log_pos         int(11)     default NULL,
  920.   master_host     varchar(60) NULL,
  921.   master_log_file varchar(32) NULL,
  922.   master_log_pos  int NULL,
  923.  
  924.   PRIMARY KEY  (host) 
  925. );
  926.  
  927. =back
  928.  
  929.  
  930. =item --suffix suffix
  931.  
  932. Each database is copied back into the originating datadir under
  933. a new name. The new name is the original name with the suffix
  934. appended. 
  935.  
  936. If only a single db_name is supplied and the --suffix flag is not
  937. supplied, then "--suffix=_copy" is assumed.
  938.  
  939. =item --allowold
  940.  
  941. Move any existing version of the destination to a backup directory for
  942. the duration of the copy. If the copy successfully completes, the backup 
  943. directory is deleted - unless the --keepold flag is set.  If the copy fails,
  944. the backup directory is restored.
  945.  
  946. The backup directory name is the original name with "_old" appended.
  947. Any existing versions of the backup directory are deleted.
  948.  
  949. =item --keepold
  950.  
  951. Behaves as for the --allowold, with the additional feature 
  952. of keeping the backup directory after the copy successfully completes.
  953.  
  954. =item --addtodest
  955.  
  956. Don't rename target directory if it already exists, just add the
  957. copied files into it.
  958.  
  959. This is most useful when backing up a database with many large
  960. tables and you don't want to have all the tables locked for the
  961. whole duration.
  962.  
  963. In this situation, I<if> you are happy for groups of tables to be
  964. backed up separately (and thus possibly not be logically consistant
  965. with one another) then you can run mysqlhotcopy several times on
  966. the same database each with different db_name./table_regex/.
  967. All but the first should use the --addtodest option so the tables
  968. all end up in the same directory.
  969.  
  970. =item --flushlog
  971.  
  972. Rotate the log files by executing "FLUSH LOGS" after all tables are
  973. locked, and before they are copied.
  974.  
  975. =item --resetmaster
  976.  
  977. Reset the bin-log by executing "RESET MASTER" after all tables are
  978. locked, and before they are copied. Useful if you are recovering a
  979. slave in a replication setup.
  980.  
  981. =item --resetslave
  982.  
  983. Reset the master.info by executing "RESET SLAVE" after all tables are
  984. locked, and before they are copied. Useful if you are recovering a
  985. server in a mutual replication setup.
  986.  
  987. =item --regexp pattern
  988.  
  989. Copy all databases with names matching the pattern
  990.  
  991. =item --regexp /pattern1/./pattern2/
  992.  
  993. Copy all tables with names matching pattern2 from all databases with
  994. names matching pattern1. For example, to select all tables which
  995. names begin with 'bar' from all databases which names end with 'foo':
  996.  
  997.    mysqlhotcopy --indices --method=cp --regexp /foo$/./^bar/
  998.  
  999. =item db_name./pattern/
  1000.  
  1001. Copy only tables matching pattern. Shell metacharacters ( (, ), |, !,
  1002. etc.) have to be escaped (e.g. \). For example, to select all tables
  1003. in database db1 whose names begin with 'foo' or 'bar':
  1004.  
  1005.     mysqlhotcopy --indices --method=cp db1./^\(foo\|bar\)/
  1006.  
  1007. =item db_name./~pattern/
  1008.  
  1009. Copy only tables not matching pattern. For example, to copy tables
  1010. that do not begin with foo nor bar:
  1011.  
  1012.     mysqlhotcopy --indices --method=cp db1./~^\(foo\|bar\)/
  1013.  
  1014. =item -?, --help
  1015.  
  1016. Display helpscreen and exit
  1017.  
  1018. =item -u, --user=#         
  1019.  
  1020. user for database login if not current user
  1021.  
  1022. =item -p, --password=#     
  1023.  
  1024. password to use when connecting to the server. Note that you are strongly
  1025. encouraged *not* to use this option as every user would be able to see the
  1026. password in the process list. Instead use the '[mysqlhotcopy]' section in
  1027. one of the config files, normally /etc/my.cnf or your personal ~/.my.cnf.
  1028. (See the chapter 'my.cnf Option Files' in the manual)
  1029.  
  1030. =item -h, -h, --host=#
  1031.  
  1032. Hostname for local server when connecting over TCP/IP.  By specifying this
  1033. different from 'localhost' will trigger mysqlhotcopy to use TCP/IP connection.
  1034.  
  1035. =item -P, --port=#         
  1036.  
  1037. port to use when connecting to MySQL server with TCP/IP.  This is only used
  1038. when using the --host option.
  1039.  
  1040. =item -S, --socket=#         
  1041.  
  1042. UNIX domain socket to use when connecting to local server
  1043.  
  1044. =item  --noindices          
  1045.  
  1046. Don\'t include index files in copy. Only up to the first 2048 bytes
  1047. are copied;  You can restore the indexes with isamchk -r or myisamchk -r
  1048. on the backup.
  1049.  
  1050. =item  --method=#           
  1051.  
  1052. method for copy (only "cp" currently supported). Alpha support for
  1053. "scp" was added in November 2000. Your experience with the scp method
  1054. will vary with your ability to understand how scp works. 'man scp'
  1055. and 'man ssh' are your friends.
  1056.  
  1057. The destination directory _must exist_ on the target machine using the
  1058. scp method. --keepold and --allowold are meaningless with scp.
  1059. Liberal use of the --debug option will help you figure out what\'s
  1060. really going on when you do an scp.
  1061.  
  1062. Note that using scp will lock your tables for a _long_ time unless
  1063. your network connection is _fast_. If this is unacceptable to you,
  1064. use the 'cp' method to copy the tables to some temporary area and then
  1065. scp or rsync the files at your leisure.
  1066.  
  1067. =item -q, --quiet              
  1068.  
  1069. be silent except for errors
  1070.  
  1071. =item  --debug
  1072.  
  1073. Debug messages are displayed 
  1074.  
  1075. =item -n, --dryrun
  1076.  
  1077. Display commands without actually doing them
  1078.  
  1079. =back
  1080.  
  1081. =head1 WARRANTY
  1082.  
  1083. This software is free and comes without warranty of any kind. You
  1084. should never trust backup software without studying the code yourself.
  1085. Study the code inside this script and only rely on it if I<you> believe
  1086. that it does the right thing for you.
  1087.  
  1088. Patches adding bug fixes, documentation and new features are welcome.
  1089. Please send these to internals@lists.mysql.com.
  1090.  
  1091. =head1 TO DO
  1092.  
  1093. Extend the individual table copy to allow multiple subsets of tables
  1094. to be specified on the command line:
  1095.  
  1096.   mysqlhotcopy db newdb  t1 t2 /^foo_/ : t3 /^bar_/ : +
  1097.  
  1098. where ":" delimits the subsets, the /^foo_/ indicates all tables
  1099. with names begining with "foo_" and the "+" indicates all tables
  1100. not copied by the previous subsets.
  1101.  
  1102. newdb is either another not existing database or a full path to a directory
  1103. where we can create a directory 'db'
  1104.  
  1105. Add option to lock each table in turn for people who don\'t need
  1106. cross-table integrity.
  1107.  
  1108. Add option to FLUSH STATUS just before UNLOCK TABLES.
  1109.  
  1110. Add support for other copy methods (eg tar to single file?).
  1111.  
  1112. Add support for forthcoming MySQL ``RAID'' table subdirectory layouts.
  1113.  
  1114. =head1 AUTHOR
  1115.  
  1116. Tim Bunce
  1117.  
  1118. Martin Waite - added checkpoint, flushlog, regexp and dryrun options
  1119.                Fixed cleanup of targets when hotcopy fails. 
  1120.            Added --record_log_pos.
  1121.                RAID tables are now copied (don't know if this works over scp).
  1122.  
  1123. Ralph Corderoy - added synonyms for commands
  1124.  
  1125. Scott Wiersdorf - added table regex and scp support
  1126.  
  1127. Monty - working --noindex (copy only first 2048 bytes of index file)
  1128.         Fixes for --method=scp
  1129.  
  1130. Ask Bjoern Hansen - Cleanup code to fix a few bugs and enable -w again.
  1131.  
  1132. Emil S. Hansen - Added resetslave and resetmaster.
  1133.  
  1134. Jeremy D. Zawodny - Removed depricated DBI calls.  Fixed bug which
  1135. resulted in nothing being copied when a regexp was specified but no
  1136. database name(s).
  1137.  
  1138. Martin Waite - Fix to handle database name that contains space.
  1139.  
  1140. Paul DuBois - Remove end '/' from directory names
  1141.